<?php

namespace Caifenglei\AuthRbac\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $guarded = [
        'id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
        'pivot'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
    ];

    public const IDENTITY_TEACHER = 1;
    public const IDENTITY_STUDENT = 2;
    public const IDENTITY_GUARDIAN = 3;

    const ID_TEACHER = 'teacher';
    const ID_STUDENT = 'student';
    const ID_GUARDIAN = 'guardian';
    const ID_ADMIN = 'admin'; //系统管理员

    public const STATUS_AVAILABLE = 1;
    public const STATUS_FORBIDDEN = 0;

    public const GENDER_MALE = 1;
    public const GENDER_FEMALE = 2;
    public const GENDER_UNKNOWN = 0;

    public const PASSWORD_INIT = 0; //初始化密码
    public const PASSWORD_SET = 1;  //密码已重设置
    public const PASSWORD_WEEK = 2; //弱密码

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier(): mixed
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims(): array
    {
        return [];
    }

    /**
     * @return MorphTo
     */
    public function identifiable(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * 是否超级管理员
     * @return bool
     */
    public function isSuperAdmin(): bool
    {
        return $this->is_admin === 1;
    }

    /**
     * 定义初始化密码
     * 前缀+账号后六位（不足的补0）+后缀: yyyyxxxxxx -> xxJy@xxxxxx!     xxx -> xxJy@xxx000!
     */
    public static function getInitPassword($salt): string
    {
        $salt = substr(str_pad($salt, 6, '0', STR_PAD_RIGHT), -6);
        return config('auth-rbac.passwords.init.prefix').$salt.config('auth-rbac.passwords.init.suffix');
    }

    public static function getUserByInfo($info) {

        $user = static::where('username', $info['username'])->first();
        if(!$user) {

            $user = static::create([
                'username' => $info['username'],
                'password' => self::getInitPassword($info['username']),
                'last_ip' => $info['last_ip'],
                'last_time' => now()
            ]);
        }
        return $user;
    }
}
